package com.apps.ftapp.fragment;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.apps.ftapp.R;
import com.apps.ftapp.adapter.ExamRadioAdapter;
import com.apps.ftapp.bean.ExamQuestion;
import com.apps.ftapp.bean.QuestionEntry;
import com.apps.ftapp.custom.RadioGroupListView;
import com.apps.ftapp.ui.IExamResponseListener;
import com.apps.ftapp.util.L;
import com.apps.ftapp.util.ScreenUtils;
import com.zzhoujay.richtext.ImageHolder;
import com.zzhoujay.richtext.RichText;
import com.zzhoujay.richtext.callback.ImageFixCallback;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * A simple {@link Fragment} subclass.
 */
public class ExamRadioJXFragment extends Fragment {


    private static final String ARG_QUESTION = "arg_question";
    private static final String ARG_MATERIAL = "arg_material";
    private static final int REQUESTCODE = 100;

    @BindView(R.id.txt_exam_title)
    TextView mTxtTitle;
    @BindView(R.id.txt_exam_progress)
    TextView mTxtProgress;
    @BindView(R.id.rl_exam_title)
    RelativeLayout mRelativeLayoutTitle;
    @BindView(R.id.view_place)
    View mViewPlace;
    @BindView(R.id.txt_exam_content)
    TextView mTxtContent;
    @BindView(R.id.txt_analysis)
    TextView mTxtAnalysis;
    @BindView(R.id.ll_analysis)
    LinearLayout mLlAnalysis;
    Unbinder unbinder;
    @BindView(R.id.radio_group_exam)
    RadioGroupListView mRadioGroup;
    @BindView(R.id.zhengquedaan)
    TextView zhengquedaan;
    @BindView(R.id.zuodabenti)
    TextView zuodabenti;
    @BindView(R.id.huidazhengque)
    TextView huidazhengque;
    @BindView(R.id.huidacuowu)
    TextView huidacuowu;
    @BindView(R.id.delivercompanyname)
    TextView delivercompanyname;
    @BindView(R.id.beidati)
    TextView beidati;
    @BindView(R.id.cuowulv)
    TextView cuowulv;
    @BindView(R.id.yixuanxiang)
    TextView yixuanxiang;
    @BindView(R.id.jiexi)
    WebView jiexi;


    //

    //


    private IExamResponseListener mResponseListener;
    ExamRadioAdapter mRadioAdapter;

    ExamQuestion mExamQuestion;
    QuestionEntry mQuestionEntry;

    boolean isMaterialMode;//是否是材料题
    int position_whichOne;//第几个题
    int screen_width;

    public ExamRadioJXFragment() {
        // Required empty public constructor
    }

    public static ExamRadioFragment newInstance(QuestionEntry entry, boolean isMaterial) {

        Bundle args = new Bundle();
        args.putParcelable(ARG_QUESTION, entry);
        args.putBoolean(ARG_MATERIAL, isMaterial);

        ExamRadioFragment fragment = new ExamRadioFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof IExamResponseListener) {
            mResponseListener = (IExamResponseListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mQuestionEntry = getArguments().getParcelable(ARG_QUESTION);
            isMaterialMode = getArguments().getBoolean(ARG_MATERIAL, false);

            mExamQuestion = mQuestionEntry.getExamQuestion();
            position_whichOne = mQuestionEntry.getPosition();
        }
        screen_width = ScreenUtils.getScreenWidth(getContext()) - getResources().getDimensionPixelSize(R.dimen.fab_margin) * 2;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_exam_radio_jx, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        refreshView();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUESTCODE && resultCode == Activity.RESULT_OK) {
//            ExamNote examNote = data.getParcelableExtra("note");
//            mExamQuestion.setNote(examNote);
            refreshView();
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mResponseListener = null;
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    public void refreshView() {

        L.i("main", "....refreshView.../..");
        mTxtTitle.setText(mQuestionEntry.getTitle());
        mTxtProgress.setText((position_whichOne + 1) + "/" + mQuestionEntry.getCount());


//        RichText.fromHtml((isMaterialMode ? "【选项】" : "【单选题】") + mExamQuestion.getStem())
        RichText.fromHtml(mExamQuestion.getStem())
                .autoFix(false)
                .scaleType(ImageHolder.ScaleType.FIT_XY)
                .resetSize(true)
                .size(ImageHolder.WRAP_CONTENT, ImageHolder.WRAP_CONTENT)
                .fix(new ImageFixCallback() {
                    @Override
                    public void onInit(ImageHolder holder) {

                    }

                    @Override
                    public void onLoading(ImageHolder holder) {

                    }

                    @Override
                    public void onSizeReady(ImageHolder holder, int imageWidth, int imageHeight, ImageHolder.SizeHolder sizeHolder) {

                    }

                    @Override
                    public void onImageReady(ImageHolder holder, int width, int height) {

                        if (width * 2 > screen_width) {
                            holder.setWidth(screen_width);
                            holder.setHeight(height * 2 * screen_width / (width * 2));
                        } else {
                            holder.setWidth(width * 2);
                            holder.setHeight(height * 2);
                        }

                    }

                    @Override
                    public void onFailure(ImageHolder holder, Exception e) {

                    }
                })
                .into(mTxtContent);

        mRadioAdapter = new ExamRadioAdapter(getActivity(), mExamQuestion, mQuestionEntry.getExam_or_analysis() != 1);
        mRadioGroup.setAdapter(mRadioAdapter);

        //答题模式
        if (mQuestionEntry.getExam_or_analysis() != 1) {

            for (int i = 0; i < mRadioGroup.getChildCount(); i++) {
                final int _position = i;
                View radiobutton = mRadioGroup.getChildAt(i);
                radiobutton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mResponseListener.onRadio(mExamQuestion.getDataList().get(_position).getId(), position_whichOne);
                    }
                });
            }

//            mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
//                @Override
//                public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {
//                    mResponseListener.onRadio(mExamQuestion.getDataList().get(i).getId(), position_whichOne);
//                }
//            });
        }

        //错误分析模式
//        if (mQuestionEntry.getExam_or_analysis() == 1) {
        if (mQuestionEntry.getExam_or_analysis() == 1) {

            mLlAnalysis.setVisibility(View.VISIBLE);
            RichText.fromHtml(mExamQuestion.getAnalysis())
                    .autoFix(false)
                    .scaleType(ImageHolder.ScaleType.FIT_XY)
                    .size(ImageHolder.WRAP_CONTENT, ImageHolder.WRAP_CONTENT)
                    .resetSize(true)
                    .fix(new ImageFixCallback() {
                        @Override
                        public void onInit(ImageHolder holder) {

                        }

                        @Override
                        public void onLoading(ImageHolder holder) {

                        }

                        @Override
                        public void onSizeReady(ImageHolder holder, int imageWidth, int imageHeight, ImageHolder.SizeHolder sizeHolder) {

                        }

                        @Override
                        public void onImageReady(ImageHolder holder, int width, int height) {

                            if (width * 2 > screen_width) {
                                holder.setWidth(screen_width);
                                holder.setHeight(height * 2 * screen_width / (width * 2));
                            } else {
                                holder.setWidth(width * 2);
                                holder.setHeight(height * 2);
                            }

                        }

                        @Override
                        public void onFailure(ImageHolder holder, Exception e) {

                        }
                    })
                    .into(mTxtAnalysis);


        }

        //如果是材料题
        if (isMaterialMode) {
            mRelativeLayoutTitle.setBackgroundColor(getResources().getColor(R.color.index_title_color));
            mViewPlace.setVisibility(View.GONE);

            jiexi.loadData(mExamQuestion.getAnalysis(), "text/html; charset=UTF-8", null);

            //jiexi

            zhengquedaan.setText(mExamQuestion.getAnswer());
            //        jiexi.set

            zhengquedaan.setText(mExamQuestion.getPersonal().getDo_count() + "次");
            huidazhengque.setText(mExamQuestion.getPersonal().getRight_count() + "次");
            huidacuowu.setText(mExamQuestion.getPersonal().getWrong_count() + "次");
            //jiexi


            //

            beidati.setText(mExamQuestion.getAll().getDo_count() + "次");
            cuowulv.setText(mExamQuestion.getAll().getWrong_rate());
            yixuanxiang.setText(mExamQuestion.getAll().getEasy_wrong());
            //


        }
    }
}
